<template>
  <div class="table-container">
    <a-card :title="t['价签管理']" class="mb-4">
      <HeadVue
        :query="query"
        @reload="getList"
        @display-assignment="showAssignment = true"
        :selected-keys="selectedKeys"
        @search="search"
      >
        <FormItem>
          <div>{{ t["其他"] }}</div>
          <div class="flex gap-4">
            <div v-if="isLikeAdmin">
              <a-button type="primary" @click="openModal">
                {{ t["新增"] }}
              </a-button>
            </div>
            <a-popover trigger="click" position="bottom">
              <a-button>{{ t["列配置"] }}</a-button>
              <template #content>
                <a-transfer
                  v-model:model-value="tagTableConfig.defaultField"
                  :data="transferColumns"
                  :title="[t['已隐藏'], t['已显示']]"
                  @change="setColumns"
                />
              </template>
            </a-popover>
          </div>
        </FormItem>
      </HeadVue>
      <div class="flex justify-center items-center my-4">
        <div class="relative">
          <GlobalSearch
            v-model:keyword="query.keyword"
            :placeholder="t['请输入价签编码']"
            @search="search"
            @reset="resetQuery"
            @on-focus="condition.show = true"
          />
          <div v-show="condition.show" class="condition absolute">
            <div class="flex justify-between">
              <div>{{ t["区域"] }}</div>
              <div class="cursor-pointer" @click="condition.show = false">
                <IconClose :size="16" />
              </div>
            </div>
            <a-divider margin="8px" />
            <div class="flex flex-col gap-3">
              <div class="flex items-center justify-between">
                <div class="text-nowrap">{{ t["范围"] }}</div>
              </div>
              <div>
                <a-checkbox-group
                  v-model="query.mType"
                  :default-value="[]"
                  :options="translateOptions(conditionOptions)"
                >
                </a-checkbox-group>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-card>

    <a-card>
      <a-table
        v-bind="tagTableConfig.tableConfig"
        v-model:selected-keys="selectedKeys"
        :loading="loading"
        :size="tagTableConfig.tableConfig.size"
        :columns="columnsData"
        :page-position="tagTableConfig.tableConfig.pagePosition"
        :bordered="{
          bodyCell: tagTableConfig.tableConfig.bordered.bodyCell,
          wrapper: tagTableConfig.tableConfig.bordered.wrapper,
          headerCell: tagTableConfig.tableConfig.bordered.headerCell,
          cell: tagTableConfig.tableConfig.bordered.cell
        }"
        :data="tableData"
        :row-selection="{
          showCheckedAll: true,
          type: 'checkbox',
          onlyCurrent: false
        }"
        row-key="tagId"
        :pagination="{
          pageSize: query.pageSize,
          total: query.total,
          current: query.pageNum,
          showJumper: tagTableConfig.tableConfig.pagination.showJumper,
          showPageSize: tagTableConfig.tableConfig.pagination.showPageSize,
          showTotal: tagTableConfig.tableConfig.pagination.showTotal,
          simple: tagTableConfig.tableConfig.pagination.simple,
          showMore: tagTableConfig.tableConfig.pagination.showMore
        }"
        @filter-change="filterChange"
        @sorter-change="sorterChange"
        @page-change="pageChange"
        @page-size-change="pageSizeChange"
      >
        <template #index="{ rowIndex }">
          <span>{{ rowIndex + 1 }}</span>
        </template>
        <template #imgSrc="{ record }">
          <div style="height: 60px" class="flex justify-center items-center">
            <img
              v-if="record.imgSrc"
              :src="record.imgSrc"
              :preview="false"
              class="image"
              height="60"
              width="100"
              @error="onError(record)"
            />
          </div>
        </template>
        <template #rssi="{ record }">
          <a-progress :percent="record.rssi / 100"></a-progress>
        </template>
        <template #soc="{ record }">
          <a-progress :percent="record.soc / 100"></a-progress>
        </template>

        <template #tagCode="{ record }">
          <div class="cursor-pointer text-nowrap" @click.stop="copyText(record.tagCode)">
            <span>{{ record.tagCode }}</span>
            <IconCopy />
          </div>
        </template>
        <template #bindMode="{ record }">
          <a-tag>{{ t[getBindMode(record.bindMode)] }}</a-tag>
        </template>
        <template #goodsName="{ record }">
          <div class="flex gap-2 justify-center">
            <template v-for="(item, key) in getTags(record.goodsName)" :key="key">
              <a-tooltip :content="item">
                <a-tag>
                  {{ item.slice(0, 6) }}
                </a-tag>
              </a-tooltip>
            </template>
          </div>
        </template>
        <template #barcode="{ record }">
          <div class="flex gap-2 justify-center">
            <template v-for="(item, key) in getTags(record.barcode)" :key="key">
              <a-tooltip :content="item">
                <a-tag>
                  {{ item.slice(0, 6) }}
                </a-tag>
              </a-tooltip>
            </template>
          </div>
        </template>
        <!-- 状态 -->
        <template #status="{ record }">
          <a-tag :color="record.status === '1' ? 'red' : 'green'">
            {{ t[isOnline(record.status)] }}
          </a-tag>
        </template>
        <template #optional="{ record }">
          <div class="flex gap-2 justify-center">
            <a-link @click="send(record)">
              {{ t["下发"] }}
            </a-link>
            <a-link @click="getHistory(record)"> {{ t["记录"] }} </a-link>
            <a-link @click="editTag(record)"> <IconEdit /> {{ t["编辑"] }} </a-link>
          </div>
        </template>
        <template #tagColor="{ record }">
          {{ deviceColorList[record.tagColor]?.label }}
        </template>
      </a-table>
    </a-card>

    <Create :ratio-list="ratioList" @reload="getList" :station-list="stationList" />
  </div>
  <a-modal
    v-model:visible="showDispatch"
    :title="t['操作']"
    fullscreen
    :footer="false"
    modal-class="my-modal"
  >
    <Dispatch />
  </a-modal>

  <a-modal
    v-if="historyModal.show"
    v-model:visible="historyModal.show"
    fullscreen
    :title="t['下发队列']"
  >
    <HistoryVue :tag-code="historyModal.tagCode" />
  </a-modal>
  <AssignmentVue v-model="showAssignment"></AssignmentVue>
</template>

<script setup lang="ts">
import { listPriceTag } from "@/api/service/priceTag/priceTag";
import { Tag } from "@/api/service/priceTag/types";
import { queryStation } from "@/api/service/station/station";
import { deviceColorList } from "@/data/options/selection";
import { getBindMode, isOnline } from "@/data/options/status";

import { getTagTableConfig } from "@/store/modules/form/form.utils";

import { camelToUnderline } from "@/utils/reg";
import { copyText, importAssets } from "@/utils/utils";
import { SelectOption, TableColumnData } from "@arco-design/web-vue";

import { queryModel } from "@/api/service/model/model";
import { ENUM_DATA_SCOPE } from "@/enum/system.enum";
import { useQuery } from "@/hook/useTableConfig";

import { userStore } from "@/store/modules/user/user";
import Dispatch from "../device/dispatch.vue";
import { dispatchParams, showDispatch } from "../device/form";
import HistoryVue from "../sendqueue/details/details.vue";
import AssignmentVue from "./assignment/Assignment.vue";
import GlobalSearch from "./components/GlobalSearch.vue";
import { columns } from "./data/columns";
import {
  form,
  resetForm,
  selectedKeys,
  showForm,
  stationList,
  tableData,
  transferColumns
} from "./data/form";
import { conditionOptions } from "./data/options";
import Create from "./head/Create.vue";
import HeadVue from "./head/Head.vue";

// const updateConfig = {
//   uploadType: "",
//   downloadType: "",
//   downloadLink: `/priceTag/priceTag/xlsx`,
//   uploadLink: `/priceTag/priceTag/xlsx`,
//   uploadText: "标签批量绑定"
// };
const t = translate("公共模块");

const columnsData = ref<TableColumnData[]>([]);

const user = userStore();
const showAssignment = ref(false);

const tagTableConfig = computed(() => {
  return getTagTableConfig();
});
const condition = ref({
  show: false,
  startTime: 0,
  endTime: 0
});

const keyword = ref("");
const historyModal = ref({
  show: false,
  tagCode: "",
  id: ""
});

const getHistory = (record: { tagCode: string }) => {
  copyText(record.tagCode);
  historyModal.value.show = true;
  historyModal.value.tagCode = record.tagCode;
};

const onError = (item: Tag) => {
  item.imgSrc = importAssets("image/error.png");
};
const loading = ref(false);

const ratioList = ref<Array<SelectOption>>([]);

const query = useQuery<Tag>({
  pageSize: 20,
  isAsc: "asc",
  mType: [0, 1, 2, 3, 4, 5],
  orderByColumn: "tag_code",
  keyword: "",
  scope: ENUM_DATA_SCOPE.THIS_SHOP,
  store: "",
  filterId: "",
  tagModel: ""
});

/**
 * 注释:价签尺寸列表
 *
 * */
const getResolutions = async () => {
  const result = await queryModel("all");
  ratioList.value = result.data.map((item: any) => {
    return {
      label: item.description,
      value: item.id
    };
  });
};

/* 获取价签列表 */
async function getList() {
  loading.value = true;
  /* calculate time */
  condition.value.startTime = new Date().getTime();

  try {
    const result = await listPriceTag(query.value);

    /* calculate time */

    tableData.value = result.rows?.map((e) => {
      if (e.imgSrc) {
        e.imgSrc += `?cache=${Math.random()}`;
      }
      return e;
    });

    query.value.total = result.total;
    loading.value = false;

    columns.forEach((item) => {
      if (item.dataIndex === "resolutionDesc" && item.filterable) {
        item.filterable.filter = null as any;
        item.filterable.filters = ratioList.value.map((m: any) => {
          return {
            text: m.label,
            value: m.value
          };
        });
      }
    });
  } catch (error) {
    tableData.value = [];
    loading.value = false;
  }
}
const search = () => {
  query.value.pageNum = 1;
  keyword.value = query.value.keyword;

  getList();
  condition.value.show = true;
};
const closeCondition = () => {
  condition.value.show = false;
};
document.onmousedown = (e) => {
  const target = e.target as HTMLElement;
  if (!(target.closest(".global-search") || target.closest(".condition"))) {
    closeCondition();
  }
};

onUnmounted(() => {
  document.onmousedown = null;
  selectedKeys.value = [];
  showDispatch.value = false;
});

const setColumnsData = () => {
  columnsData.value = useCloned(columns).cloned.value.filter((item) => {
    item.title = t.value?.[item.title as string];
    item.align = "center";
    if (!item.width) item.width = 120;
    item.slotName = item.dataIndex;
    return (
      Object.values(tagTableConfig.value.defaultField).findIndex((e) => e === item.dataIndex) > -1
    );
  });
};

watch(
  tagTableConfig,
  () => {
    setColumnsData();
  },
  { deep: true }
);

const getStations = async () => {
  const { data } = await queryStation();
  stationList.value = data.map((item: any) => {
    return {
      label: item.stationNum,
      value: item.stationId
    };
  });
};

// const getStoreList = async () => {
//   if (storeList.value.length === 0) {
//     const data = await listStore({ pageNum: 1, pageSize: 100 });
//     storeList.value = data.rows.map((e) => {
//       return {
//         label: e.storeName,
//         value: e.id
//       };
//     });
//   }
// };

onMounted(async () => {
  await getStations();
  await getResolutions();
  await getList();
  // await getStoreList();
  setColumnsData();
});

function pageChange(index: number) {
  query.value.pageNum = index;
  getList();
}

async function editTag(tag: Tag) {
  form.value = tag;
  showForm.value = true;
}
const getTags = (tagName: string): string[] => {
  if (!tagName) {
    return [];
  }
  if (tagName.includes(",")) {
    return tagName.split(",");
  }
  return [tagName];
};
const setColumns = () => {
  if (tagTableConfig.value.defaultField.length === 0) {
    tagTableConfig.value.defaultField = [
      "index",
      "tagCode",
      "storeName",
      "refreshTimes",
      "resolutionDesc",
      "centigrade",
      "soc",
      "optional"
    ];
  }
};

/**
 * 注释: 重置搜索
 *
 * */
const resetQuery = () => {
  selectedKeys.value = [];
  query.value.keyword = "";
  getList();
};
const sorterChange = (columnName: string, asc: string) => {
  query.value.isAsc = asc.replace("end", "") as any;
  query.value.orderByColumn = camelToUnderline(columnName);
  getList();
};

const pageSizeChange = (size: number) => {
  query.value.pageSize = size;
  getList();
};

/* 打开模态框 */
const openModal = () => {
  resetForm();
  showForm.value = true;
};

const filterChange = (dataIndex: string, filteredValues: string[]) => {
  if (dataIndex === "resolutionDesc") {
    dataIndex = "resolutionId";
  }
  query.value.pageNum = 1;
  query.value[dataIndex] = filteredValues[0];
  getList();
};

/**
 * 注释: 下发
 *
 * */
const send = (item: Tag) => {
  form.value = item;
  dispatchParams.value.goodsList = item.goodsList;

  dispatchParams.value.selectedGoods = item.goodsList?.map((e) => e.value);
  showDispatch.value = true;
  dispatchParams.value.templateId = item.templateId;
};

/* 超管和超管创建的账号可显示 */
const isLikeAdmin = computed(() => {
  const u = user.user;
  return u.admin || u.deptId === "0";
});
</script>

<style scope lang="scss">
@use "./index";
</style>
